package com.pandas.community.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Aspect
public class ServiceLogAspect {


    private static final Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);

    @Pointcut("execution(* com.pandas.community.service.*.*(..))")
    public void pointcut(){

    }


    @Before("pointcut()")
    public void berfore(JoinPoint joinPoint){
        //JointPoint 切入方法实体
        //用户[],在[]，访问了[com.pandas.community.service.xxx()]
        String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        String target = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();


        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        /**
         * 之前是controller调用service
         * 现在consumer也会调用service，没有request
         */
        if(attributes == null){
            logger.info(String.format("EventConsumer, 在[%s], 访问了[%s].", now, target));
        }else{
            HttpServletRequest request = attributes.getRequest();
            String ip = request.getRemoteHost();
            logger.info(String.format("用户[%s], 在[%s], 访问了[%s].", ip, now, target));
        }
    }

}
